import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

class PostService {
  final httpClient = FakeHttpClient();
  Future<Post> getOnePost() async {
    try {
      final responseBody = await httpClient.getResponseBody();
      return Post.fromJson(responseBody);
    } on SocketException {
      throw Failure('暂无网络 😑'); //! 无网络异常
    } on HttpException {
      throw Failure('找不到文件 😱'); //! 404
    } on FormatException {
      throw Failure('失效JSON 👎'); //! 无效JSON
    }
  }
}

class Failure {
  Failure(this.message);

  final String message;

  @override
  String toString() => message;
}

class FakeHttpClient {
  Future<String> getResponseBody() async {
    await Future.delayed(Duration(milliseconds: 500));
    // throw SocketException('暂无网络'); //! 无网络异常
    // throw HttpException('找不到文件'); //! 404
    // throw FormatException('失效JSON'); //! 无效JSON
    return '{"userId":1,"id":1,"title":"nice title","body":"cool body"}';
  }
}

class Post {
  final int id;
  final int userId;
  final String title;
  final String body;

  Post({
    @required this.id,
    @required this.userId,
    @required this.title,
    @required this.body,
  });

  static Post fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    return Post(
      id: map['id'],
      userId: map['userId'],
      title: map['title'],
      body: map['body'],
    );
  }

  static Post fromJson(String source) => fromMap(json.decode(source));

  @override
  String toString() => '编号: $id, 用户编号: $userId, 标题: $title, 响应体: $body';
}
